<?php


function CheckPaymentComplete($get_data=""){

	global $wpdb;
	 
	if(isset($get_data['order_id'])){
	 
		$result = mysql_query("SELECT order_status, order_items, cus_id, order_shipping FROM wp_shopperpress_orders WHERE wp_shopperpress_orders.order_id='".strip_tags($get_data['order_id'])."' LIMIT 1", $wpdb->dbh) 
		or die(mysql_error().' on line: '.__LINE__);
					
		$array = mysql_fetch_assoc($result);

		if(get_option("shopperpress_system") =="credit"){
		mysql_query("UPDATE $wpdb->usermeta SET meta_value=meta_value+".get_option('credit_del_'.$array['order_shipping'])." WHERE meta_key='aim' AND user_id='".$array['cus_id']."' LIMIT 1");
		//die(print_r($array).get_option('credit_del_'.$array['order_shipping']));
		}
		
		return $array; 
	
	}else{
	
		return "failed";
	
	}



}

function CheckPaymentGateways($post_data=""){

global $wpdb;

	if(!array($post_data)){ return "none";  }
	
	// CHECK FOR PAYPAL
	if(isset($post_data['mc_gross'])){

		return "paypal";
	
	}
	
	
	// CHECK FOR PAYPAL
	if(isset($post_data['x_response_code'])){

		return "authorize";
	
	}	

	return "none";
}




function CheckPaymentStatus($which, $post_data){

global $wpdb;

// ORDER STATUS
// 0 = AWAITING PAYMENT
// 3 = PAID
// 5 = Payment Received
// 6 = payment failed
// 7 = payment pending
// 8 = payment refunded

	switch($which){
	
	
		case "authorize": {
		
			$order_id 	= $post_data['x_cust_id'];
			
			UpdateOrderStatus(5, $order_id, $post_data);
			return "thankyou";
		
		
		} break;
	
		case "paypal": {
 
			//$OrderID 	= explode("-",$post_data['custom']);
			$order_id 	= $post_data['custom'];
 
            if ($post_data['payment_status'] == "Completed"){

				UpdateOrderStatus(5, $order_id, $post_data);
				return "thankyou";

            }
			elseif ($post_data['payment_status'] =="Pending"){

				UpdateOrderStatus(7, $order_id, $post_data);
				return "pending";
				
			
			} elseif ( ($post_data['payment_status'] == 'Reversed') || ($post_data['payment_status'] == 'Refunded') ) {
			
				UpdateOrderStatus(8, $order_id, $post_data);

			}else{ // failed // error

				UpdateOrderStatus(6, $order_id, $post_data);

			}

			return "error";
		
		} break;


		default: { 		
		
			UpdateOrderStatus(5, $order_id, $post_data);
			return "thankyou";
		
		} break;

	}
}

function UpdateOrderStatus($status, $order_id, $post_data){

	global $wpdb;

	mysql_query("UPDATE wp_shopperpress_orders SET 
	order_status='".$status."'
	WHERE order_id='".$order_id."' LIMIT 1");

}



	function SaveOrder($form, $sendEmail){
	
	if(!isset($form['orderid']) || strlen($form['orderid']) < 2){ return; }

	global $wpdb; global $userdata; get_currentuserinfo(); $order=array();

		// MAKE ADDRESS
		$order['address'] = "\r\n ========== Customer/Shipping Address ========== \r\n\r\n";
		if(is_array($form['billing'])){
			foreach($form['billing'] as $key => $value){
				if($key !="cus_id"){
					$order['address'] .= "\r\n".$key.": ".$value." \r\n";
				}
			}
		}
		// MAKE ORDER DATA
		$order['data']  = "\r\n ========== Order Items ========== \r\n\r\n\n";
		$order['items'] ="";
			foreach($_SESSION['ddc']['productsincart'] as $key => $value) { 
			
			// CHECK IF THIS IS A MODIFIED ITEM
			
			$pos = strpos($key, '000');				
			if ($pos === false) {
			 	$key1 = $key;
			} else {
				$f = explode("000",$key);
				$key1 =$f[0];
			}

			$order['data'] .= "\r\n --------- Item ID: ". $key1. " ------------- \r\n";
			$order['data'] .= "\r\n Name: ".preg_replace('/[^\w\d_ -]/si', '',getProductName($key1)). "\r\n";
			$order['data'] .= "\r\n Qty: ".$value." \r\n";
			$order['items'] .="             ".$key1."x".$value." \r\n";

			if(isset($_POST['ShippingMethod'])){
				$order['data']  = "\r\n ========== Shipping Cost ========== \r\n\r\n";
				$order['data'] .="\r\n Shipping Method Cost: ". $_SESSION['currency_symbol'].$_POST['ShippingMethod']. " \r\n";
			}
			
			// REDUCE THE QTY FOR EACH ITEM BY ONE
			mysql_query("UPDATE $wpdb->postmeta SET meta_value=meta_value-".$value." WHERE meta_key='qty' AND post_id='".$key1."' LIMIT 1");

			// ADD PRODUCT SIZES TO EMAIL
			if(isset($_SESSION['ddc'][$key]['size']) && $_SESSION['ddc'][$key]['size'] !="na"){
					$order['data'] .="\r\n ". get_option('custom_field1'). ": ". $_SESSION['ddc'][$key]['size']. " \r\n"; 
			}
	
			if(isset($_SESSION['ddc'][$key]['color']) && $_SESSION['ddc'][$key]['color'] !="na"){
					$order['data'] .="\r\n ". get_option('custom_field2'). ": ". $_SESSION['ddc'][$key]['color']. " \r\n";
			} 

			if(isset($_SESSION['ddc'][$key]['extra']) && $_SESSION['ddc'][$key]['extra'] !="na"){
					$order['data'] .="\r\n ". get_option('custom_field3'). ": ". $_SESSION['ddc'][$key]['extra']. " \r\n";
			} 
			
			}

		// CHECK THIS ORDER ID DOESNT ALREADY EXIST		
		if($form['price']['total'] > 0){
		
		if($GLOBALS['shopperpress']['system'] =="credit"){
			$form['price']['shipping'] = $_SESSION['ddc'][$key]['size'];
		}
		
		// SAVE ORDER DATA
		mysql_query("INSERT INTO wp_shopperpress_orders (		
		cus_id,
		order_id,
		order_date,
		order_time,
		order_data,
		order_items,
		order_address,
		order_country,
		order_phone,
		order_email,
		order_total,
		order_shipping
		)
		VALUES ( '".$userdata->ID."', '".$form['orderid']."', NOW(), NOW(), '".str_replace("'","",$order['data']). "\r\n\r\n" .str_replace("'","",strip_tags($form['billing']['comments']))."','".$order['items']."', '".$order['address']."', '".$form['billing']['country']."', '".$form['billing']['phone']."', '".$form['billing']['email']."', '".str_replace(",","",$form['price']['total'])."', '".str_replace(",","",$form['price']['shipping'])."')");
		
		}
 
 		// EMAIL NOTIFICATION
		if($sendEmail){

			
			$message  = $order['data'];
			$message .= $order['address']; 	
			$message .= "\r\nTotal Price: ".$_SESSION['currency_symbol'].$form['price']['total']."\r\n";
			$to      = get_option("shipping_email");
			$subject = 'Shop Order ('.$form['orderid'].")";

			$headers = 'From: Admin <'.get_option("shipping_email").'>' . "\r\n" .
			'Reply-To: '.get_option("shipping_email").'' . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
	
			// To send HTML mail, the Content-type header must be set
			$headers  .= 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
	
			if(get_option("shipping_ccemail") !=""){
				$headers .= 'Cc: '.get_option("shipping_ccemail").'' . "\r\n";
			}
			if(get_option("shipping_bccemail") !=""){
				$headers .= 'Bcc: '.get_option("shipping_bccemail").'' . "\r\n";
			}
			wp_mail( $to, $subject, $message, $headers);
	
			
		}

	// CLEAR SESSIONS TO STOP DOUBLE ORDERING
	//session_destroy();

	return $order['data'];

	
	}




function CheckOrderData($data,$gateway=""){

	global $wpdb;
	
	switch($gateway){
	
		case "authorize": {
			$order_id 	= $data['x_cust_id'];
		} break;
		case "paypal": {
			$order_id 	= $data['custom'];
		} break;
		default: { } break;
	
	}
	
	$result = mysql_query("SELECT * FROM wp_shopperpress_orders WHERE wp_shopperpress_orders.order_id='".$order_id."' LIMIT 1", $wpdb->dbh) 
	or die(mysql_error().' on line: '.__LINE__);
				
	$array = mysql_fetch_assoc($result);
	
	return $array;

}


function shopperpress_GetMyOrders($user_id){
	
	global $wpdb; global $userdata; get_currentuserinfo(); $content="";

	if(!is_numeric($user_id)){ die("nice try!"); }

	$SQL = "SELECT * FROM wp_shopperpress_orders WHERE cus_id='".$user_id."' GROUP BY order_id ORDER BY autoid DESC"; 
 

	$posts = mysql_query($SQL, $wpdb->dbh) or die(mysql_error().' on line: '.__LINE__);
		
	  if ($posts && mysql_num_rows($posts) > 0) {
 
		while ($thepost = mysql_fetch_object($posts)) {
		
		if($thepost->order_status ==0){  
		$status = "Awaiting Payment";
		}elseif($thepost->order_status ==3){ 
		$status = "<b style='color:green;'>Paid & Completed</b>";
		}elseif($thepost->order_status ==5){ 
		$status = "<b style='color:green;'>Payment Received</b>";
		}elseif($thepost->order_status ==6){  
		$status = "<b style='color:red;'>Payment Failed</b>";
		}elseif($thepost->order_status ==7){ 
		$status = "<b style='color:blue;'>Payment Pending</b>";
		}elseif($thepost->order_status ==8){ 
		$status = "<b>Payment Refunded</b>";
		}  
		
		$content .= 
		"<tr>
        	<td>".$thepost->order_id."</td>            
            <td>".$GLOBALS['shopperpress']['currency_code'].ShopperPressMoneyFormat($thepost->order_total)."</td>
            <td>".$thepost->order_date."</td>
			<td>".$status."</td>
        	<!--<td align='center'> View Invoice </td>-->
    	</tr>";	
		
		}
		
	}else{
	
	
	}
	
	return $content;

}



?>